
const {spawn} = require('child_process');
const REGEX = {
    TRID : /TRID: '\d+'/m,
    RX_PACKAGES : /^rx_packets=(\d*)/,
    TX_PACKAGES : /^tx_packets=(\d*)/,
    RX_BYTES : /^rx_bytes=(\d*)/,
    TX_BYTES : /^tx_bytes=(\d*)/,
    CONN_TIME: /^connected_time=(\d*)/,
    SIGNAL:/signal=(-*\d*)/,
    LINESPLITE : /[\r\n]/
}
function run(cmd,params,{onData,onError,onClose}){
    console.log(cmd,params);
        const mbim_cli = spawn(cmd,params,{detached : false});
        mbim_cli.stdout.on('data', (data) => {
          console.log("ondata:",data.toString());
          onData && onData(data);
        });
        
        mbim_cli.stderr.on("data",(data)=>{
           console.log("onerror:",data.toString());
           onError && onError(data);
        });
        
        mbim_cli.on("close",(code,signal) =>{
           console.log("onclose:",code);
           onClose && onClose(code,signal);
        });
    }
const regTest = "[/dev/cdc-wdm0] Session not closed:\r\n"+
"	    TRID: '3'";
//const match = REGEX.TRID.exec(regTest);
//console.log(match);
/*
run('mbimcli',['-d', '/dev/cdc-wdm0','--query-subscriber-ready-status','--no-close'],{
            onData : (data)=>{
                const strData = data.toString();
                const match = REGEX.TRID.exec(strData);
                console.log(match);
            },
            onClose : (code,data)=>{
                if (code !== 0){
                    console.log('program exit with error. code:${code}');
                }
            },
        });
*/

const IPV4_IP = /IP \[\d\]: '(\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3})\/(\d{1,3})'/m;
const IPV4_GATEWAY = /Gateway: '(\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3})'/m;
const IPV4_DNS = /DNS \[\d\]: '(\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3})'/gm;

const _parseStringValue = (data,regex)=>{
    const match = data.match(regex);
    if(match){
        let res = []; 
        for( let i = 1; i< match.length;i++){
            res.push(match[i]);
        }
        return res.length>1?res:res[0];
    }else{
        return null;
    }
}
const _parseStringArrayValue = (data,regex)=>{
    const match = data.matchAll(regex);
    if(match){
        const matchArr = Array.from(match);
        let res = []; 
        for(let j=0;j<matchArr.length;j++){
            let subRs = [];
            let subMatch = matchArr[j];
            for( let i = 1; i< subMatch.length;i++){
                subRs.push(subMatch[i]);
            }
            res.push(subRs.length>1?subRs:subRs[0]);
        }
        return res;
    }else{
        return null;
    }
}

const Ipv4Data = "[/dev/cdc-wdm0] IPv4 configuration available: 'address, gateway, dns, mtu'\n"
+"\tIP [0]: '10.61.167.147/29'\n"
+"\tGateway: '10.61.167.145'\n"
+"\tDNS [0]: '221.179.155.193'\n"
+"\tDNS [1]: '221.179.155.209'\n"
+"\n"
+"\tMTU: '1500'";

console.log("IP:",_parseStringValue(Ipv4Data,IPV4_IP));
console.log("GATEWAY:",_parseStringValue(Ipv4Data,IPV4_GATEWAY));
console.log("DNS",_parseStringArrayValue(Ipv4Data,IPV4_DNS));

